package codeRandomThoughts.Test20有效的括号;

import java.util.Stack;

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        char ch;

        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);

            //碰到左括号,把对应的右括号入栈
            if (ch == '(')
                stack.push(')');
            else if (ch == '[')
                stack.push(']');
            else if (ch == '{')
                stack.push('}');
                //stack为空说明右括号多,stack栈顶元素不等于ch说明括号顺序有误
            else if (stack.isEmpty() || stack.peek() != ch)
                return false;
            else
                stack.pop();
        }
        return stack.isEmpty();
    }


    /**
     * 错误的算法
     * @param s
     * @return
     */
    public boolean isValid2(String s) {
        int sum = 0;
        char ch;
        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);

            //碰到左括号,把对应的右括号入栈
            if (ch == '(')
                sum += 1;
            else if (ch == '[')
                sum += 100;
            else if (ch == '{')
                sum += 10000;
            else if (ch == ')')
                sum -= 1;
            else if (ch == ']')
                sum -= 100;
            else if (ch == '}')
                sum -= 10000;

            if (sum < 0) {
                return false;
            }
        }
        return sum == 0;
    }
}
